package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

    /**
     * 拦截资源之前
     *
     * @param request
     * @param response
     * @param handler
     * @return boolean 返回true则表示放行, 反之不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取登录用户
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId != null) {
            log.info("后端用户已登录，用户id为：{}", empId);
            long id = Thread.currentThread().getId();
            log.info("线程id为：{}", id);
            BaseContext.setCurrentId(empId);
            //有, 放行
            return true;
        }

        Long userId = (Long) request.getSession().getAttribute("user");
        if (userId != null) {
            log.info("前端用户已登录，用户id为：{}", userId);
            long id = Thread.currentThread().getId();
            log.info("线程id为：{}", id);
            BaseContext.setCurrentId(userId);
            //有, 放行
            return true;
        }

        log.info("用户未登录");
        //没有--不放行且响应给用户跳转到登录页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return false;
    }

}
